<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>debounce</title>
  </head>
  <body>
    <div id="container"></div>
  </body>
  <script>
    var count = 1;
    var container = document.getElementById("container");

    function getUserAction(e) {
      //   console.log(e);
      container.innerHTML = count++;
    }

    function debounce(fn, wait, immediate) {
      let timeout = null;
      console.log(timeout, "timeout");
      return function () {
        let that = this;
        let arg = arguments;

        if (timeout) {
          console.log(timeout, "timeout");
          clearTimeout(timeout);
          console.log(timeout, "timeout");
        }
        if (immediate) {
          let callNow = !timeout;
          console.log(callNow, "calnow");
          timeout = setTimeout(() => {
            timeout = null;
          }, wait);
          if (callNow) fn.apply(that, arg);
        } else {
          timeout = setTimeout(() => {
            fn.apply(that, arg);
          }, wait);
        }
      };
    }
    // function debounce(event, time, flag) {
    //   let timer = null;
    //   return function (...args) {
    //     clearTimeout(timer);
    //     if (flag && !timer) {
    //       event.apply(this, args);
    //     }
    //     timer = setTimeout(() => {
    //       event.apply(this, args);
    //     }, time);
    //   };
    // }
    container.onmousemove = debounce(getUserAction, 1000, true);
  </script>
  <style>
    #container {
      width: 100%;
      height: 200px;
      line-height: 200px;
      text-align: center;
      color: #fff;
      background-color: #444;
      font-size: 30px;
    }
  </style>
</html>
